#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;

void Usage(string proc)
{
    cout << "Usage \r\t" << proc << " server_ip server_port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    // 1. 创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "socket failed " << errno << endl;
        return 2;
    }

    // client无需显式bind, 更不用listen和accept
    // 2. connect:链接服务端
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    // inet_addr函数一共做了两件事:
    // a.将点分十进制字符串形式IP转换为4字节整数
    // b.将4字节整数从主机序列转为网络序列
    server.sin_addr.s_addr = inet_addr(argv[1]);
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) == -1)
    {
        cerr << "connect server failed" << errno << endl;
        return 3;
    }

    cout << "client connect success" << endl;

    // 3. 请求服务
    while (true)
    {
        cout << "Please write# ";
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));
        fgets(buffer, sizeof(buffer) - 1, stdin);

        write(sock, buffer, strlen(buffer));

        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "server echo # " << buffer;
        }
    }
    return 0;
}